//
//  WYWRunMapViewController.m
//  SpiritWalk
//
//  Created by 王鑫 on 16/3/15.
//  Copyright © 2016年 王鑫. All rights reserved.
//

#import "WYWRunMapViewController.h"
#import <MAMapKit/MAMapKit.h>

#import <AMapSearchKit/AMapSearchAPI.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManager.h>
#import "MZTimerLabel.h" //计时器
#define kDefaultLocationZoomLevel       16.1
#define kDefaultControlMargin                22
@interface WYWRunMapViewController ()<MAMapViewDelegate, AMapSearchDelegate,CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate>{
    /**
     *  搜索定位
     */
    
    CLLocation *  _currentLocation;  //当前的位置
    UIButton *     _locationButton;
    /**
     *  第二节
     */
    AMapSearchAPI  *_search;   //搜索对象,定位功能
    UITableView *_tableView;
    NSArray *_pois;       //搜索到的结果放到数组中
    NSMutableArray *_annotations; //poi点的存放
}
@property(nonatomic,retain)MAMapView * mapView;
@property(nonatomic,assign)CGFloat latitude;
@property(nonatomic,assign)CGFloat longitude;
@property(nonatomic,assign)CGFloat newLatitude;
@property(nonatomic,assign)CGFloat newLongitude;
@property(nonatomic,strong)CLLocationManager *mgr;
@property(nonatomic,retain)UIButton * runBut;
@property(nonatomic,retain)UIButton * backBut;
@property(nonatomic,assign)BOOL GPSOpen;
@property(nonatomic,retain)UIView * backdropView;
@property(nonatomic,retain)UILabel *countDownLabel;
@property(nonatomic,assign)CGFloat  kil;
@property(nonatomic,retain)NSTimer * mapTimer;
@property(nonatomic,retain)UIView *runInfoView;
@property(nonatomic,retain)MZTimerLabel *timer;
@property(nonatomic,retain)UILabel *kilLabel;
@property(nonatomic,retain)UILabel *speedLabel;
/**
 *  离线地图的实现
 */
@property(nonatomic,retain)NSArray *sectionTitles;
@property(nonatomic,retain)NSArray *cities;//普通城市和直辖市
@property(nonatomic,retain)NSArray *provinces;//省
@property(nonatomic,retain)NSArray *municipalities;//直辖市
@property(nonatomic,retain)UITableView *downlodTableview;
@property (nonatomic,retain)UITableView *tableView;

/**
 *  定位搜索
 */
@property(nonatomic,assign)BOOL stopOrNo;    //跑步的状态
@property (nonatomic,retain) NSTimer *myTime;
@property(nonatomic,retain)UIButton *pathButton;
/**
 *  搜索
 */
@property(nonatomic,retain)UITextField *searchTextField; //
@property(nonatomic,copy)NSString * searchText;
@property(nonatomic,retain)AMapPOIAroundSearchRequest *request;
@property (nonatomic,retain)UIButton *searchTextFieldBt;



@end

@implementation WYWRunMapViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self =[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.searchText =nil;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createMap];
    [self createBack];
    [self countDownView];
    [self creaeRunInfoView];
    // Do any additional setup after loading the view.
    //高德地图授权
    /**
     *  离线地图
     */
    //[self initDownlodButton];
    /**
     *  定位
     */
    self.stopOrNo = YES;
    //定位
    [self initControls]; //初始化地位按钮

    //兴趣搜索
    [self initwithFrame]; //
 

}
-(void)creaeRunInfoView{
//跑步信息
    self.runInfoView=[[UIView alloc] initWithFrame:CGRectMake(0, -200, WIDTH, 200)];
    self.runInfoView.backgroundColor=[UIColor whiteColor];
    self.runInfoView.hidden=YES;
    [self.view addSubview:self.runInfoView];
    self.timer = [[MZTimerLabel alloc] initWithFrame:CGRectMake(0, 25, self.view.frame.size.width, 50)];
    self.timer.timerType = MZTimerLabelTypeStopWatch;
    [self.runInfoView addSubview:self.timer];
//计时器
    self.timer.timeLabel.backgroundColor = [UIColor clearColor];
    self.timer.timeLabel.font =[UIFont fontWithName:@"Helvetica-Bold" size:50];
    self.timer.timeLabel.textColor = [UIColor colorWithRed:0.13 green:0.6 blue:0.94 alpha:1];
    self.timer.timeLabel.textAlignment = NSTextAlignmentCenter; //UITextAlignmentCenter is deprecated in iOS 7.0
  
//公里数
    self.kilLabel=[UILabel new];
    [self.runInfoView addSubview:self.kilLabel];
    self.kilLabel.font =[UIFont fontWithName:@"Helvetica-Bold" size:18];
    self.kilLabel.textColor = [UIColor colorWithRed:0.13 green:0.6 blue:0.94 alpha:1];
    self.kilLabel.textAlignment=NSTextAlignmentCenter;
    self.kilLabel.text=@"距离(km):0.00";
    [self.kilLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WIDTH/2, 50));
        make.top.mas_equalTo(self.timer.mas_bottom).offset(10);
        make.left.mas_equalTo(0);
    }];
    //速度
    self.speedLabel=[UILabel new];
    [self.runInfoView addSubview:self.speedLabel];
    self.speedLabel.font =[UIFont fontWithName:@"Helvetica-Bold" size:18];
    self.speedLabel.textColor = [UIColor colorWithRed:0.13 green:0.6 blue:0.94 alpha:1];
    self.speedLabel.textAlignment=NSTextAlignmentCenter;
    self.speedLabel.text=@"速度(min/km):0.00";
    [self.speedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WIDTH/2, 50));
        make.top.mas_equalTo(self.timer.mas_bottom).offset(10);
        make.left.mas_equalTo(self.kilLabel.mas_right);
    }];
    
   
}
-(void)countDownView{
    self.backdropView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.backdropView.backgroundColor=[UIColor blackColor];
    self.backdropView.alpha=0.8;
    [self.view addSubview:self.backdropView];
    self.countDownLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH)];
    
    self.countDownLabel.textAlignment=NSTextAlignmentCenter;
    self.countDownLabel.center=self.view.center;
    self.countDownLabel.font=[UIFont systemFontOfSize:110];
    self.countDownLabel.textColor=[UIColor whiteColor];
   // self.countDownLabel.backgroundColor=[UIColor redColor];
    [self.backdropView addSubview:self.countDownLabel];
    self.backdropView.hidden=YES;
    //numLabel.backgroundColor=[UIColor redColor];
   
    
}
-(void)donghua{
    self.backdropView.hidden=NO;
    self.countDownLabel.text=@"3";
    NSLog(@"%@", self.countDownLabel.text);
    [UIView animateWithDuration:1 animations:^{
        self.countDownLabel.alpha=0;
        self.countDownLabel.text=@"3";
    } completion:^(BOOL finished) {
         self.countDownLabel.alpha=1;
        [UIView animateWithDuration:1 animations:^{
            self.countDownLabel.alpha=0;
            self.countDownLabel.text=@"2";
        } completion:^(BOOL finished) {
             self.countDownLabel.alpha=1;
            [UIView animateWithDuration:1 animations:^{
                self.countDownLabel.alpha=0;
                self.countDownLabel.text=@"1";
            } completion:^(BOOL finished) {
                self.countDownLabel.alpha=1;
                [UIView animateWithDuration:1 animations:^{
                    self.countDownLabel.alpha=0;
                    self.countDownLabel.text=@"GO";
                } completion:^(BOOL finished) {
                    self.backdropView.hidden=YES;
                     self.countDownLabel.alpha=1;
                    [self.runBut setTitle:@"结束跑步" forState:UIControlStateNormal];
                    [self.backBut setTitle:@"暂    停" forState:UIControlStateNormal];
                    self.runBut.backgroundColor=[UIColor redColor];
                     //开始定位
                   //  [self.mgr startUpdatingLocation];
                    self.runInfoView.hidden=NO;
                   [UIView animateWithDuration:1 animations:^{
                        self.runInfoView.frame=CGRectMake(0, 0, WIDTH, 150);
                   } completion:^(BOOL finished) {
                       [self.mapTimer fire];
                       [self.timer start];
                       [self addMapTimer];
                   }];
                }];
            }];
        }];
    }];
}
-(void)addMapTimer{
    self.mapTimer=[NSTimer timerWithTimeInterval:5 target:self selector:@selector(createRunLine) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.mapTimer forMode:NSDefaultRunLoopMode];
}
-(void)getGPS:(UIButton*)button{
    if ([button.titleLabel.text isEqualToString:@"结束跑步"]) {
       // [self.mgr stopUpdatingLocation];
       // [self.runBut setTitle:@"开始跑步" forState:UIControlStateNormal];
       // self.runBut.backgroundColor= [UIColor colorWithRed:1 green:0.91 blue:0.34 alpha:1];
        UIAlertController * alert=[UIAlertController alertControllerWithTitle:@"是否结束这次运动记录" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * actionOK=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (self.mapTimer !=nil) {
                [self.mapTimer  invalidate];
                self.mapTimer=nil;
            }
            [self.mgr stopUpdatingLocation];
            [super  dismissViewControllerAnimated:YES completion:^{
                [self.mapTimer  invalidate];
            }];
        }];
        UIAlertAction * actionNO=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:actionOK];
        [alert addAction:actionNO];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }else{
         [self donghua];
    }
  //  self.GPSOpen=!self.GPSOpen;
}
-(void)createMap{
    //创建高德地图
    [MAMapServices sharedServices].apiKey = @"fc3449e0365a0ce529efdead76bff0cc";
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate=self;
    
    _mapView.showsScale= NO;
    _mapView.showsUserLocation = YES;
   _mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    _mapView.distanceFilter =1;
    [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES];
    //使用自定义圆圈
    _mapView.customizeUserLocationAccuracyCircleRepresentation=YES;
    [self.view addSubview:_mapView];
   
}
-(void)createBack{
    //开始跑步or结束跑步
    self.runBut=[UIButton new];
    [self.runBut setTitle:@"开始跑步" forState:UIControlStateNormal];
    self.runBut.backgroundColor= [UIColor colorWithRed:1 green:0.91 blue:0.34 alpha:1];
    [self.runBut addTarget:self action:@selector(getGPS:) forControlEvents:UIControlEventTouchUpInside];
    self.runBut.layer.cornerRadius=5;
    self.runBut.layer.masksToBounds=NO;
    [self.view addSubview:self.runBut];
    [self.runBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WIDTH/2-20, 50));
        make.left.mas_equalTo(10);
        make.bottom.mas_equalTo(-30);
    }];
    self.backBut=[UIButton new];
    [self.backBut setTitle:@"返    回" forState:UIControlStateNormal];
    self.backBut.backgroundColor=[UIColor colorWithRed:0.31 green:0.64 blue:0.98 alpha:1];
    [self.backBut addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.backBut.layer.cornerRadius=5;
    self.backBut.layer.masksToBounds=NO;
    [self.view addSubview:self.backBut];
    [self.backBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(WIDTH/2-20, 50));
        make.right.mas_equalTo(-10);
        make.bottom.mas_equalTo(-30);
    }];
    
}
-(void)backAction:(UIButton*)button{
    if ([button.titleLabel.text isEqualToString:@"返    回"]) {
        [super dismissViewControllerAnimated:YES completion:^{
        
        }];
    }else if([button.titleLabel.text isEqualToString:@"暂    停"]){
        [self.timer pause ];
        if (self.mapTimer !=nil) {
            [self.mapTimer  invalidate];
            self.mapTimer=nil;
        }
        [self.mgr stopUpdatingLocation];
        [self.backBut setTitle:@"继    续" forState:UIControlStateNormal];
    }else{
        [self.timer start ];
        [self addMapTimer];
        [self.mgr startUpdatingLocation];
        [self.backBut setTitle:@"暂    停" forState:UIControlStateNormal];
    }
}
-(void)createRunLine{

    CLLocationCoordinate2D commonPolylineCoords[2];
        commonPolylineCoords[0].latitude = self.latitude;
        commonPolylineCoords[0].longitude = self.longitude; //初始化
        commonPolylineCoords[1].latitude =  _mapView.userLocation.coordinate.latitude;
        commonPolylineCoords[1].longitude = _mapView.userLocation.coordinate.longitude;
    
    MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:2];
        [_mapView addOverlay: commonPolyline];
    //计算两点距离
    [self countDistance];
    self.latitude=_mapView.userLocation.coordinate.latitude;
    self.longitude=_mapView.userLocation.coordinate.longitude;
}


-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
     _currentLocation = [userLocation.location copy];//用户当前的经纬度
    
    if(updatingLocation){
        if (self.latitude==0&&self.longitude==0) {
            self.latitude=userLocation.coordinate.latitude;
            self.longitude=userLocation.coordinate.longitude;
        }
      
    }
}
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]){
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        polylineView.lineWidth = 10.f;
        polylineView.strokeColor =[UIColor colorWithRed:0.31 green:0.64 blue:0.98 alpha:1 ];
        polylineView.lineJoinType = kMALineJoinMiter; //连接类型
        polylineView.lineCapType = kMALineCapRound;//端点类型
        return polylineView;
    }
    return nil;
}
//计算两点距离
-(void)countDistance{
         //根据经纬度创建两个位置对象
         CLLocation *loc1=[[CLLocation alloc]initWithLatitude:self.latitude longitude:self.longitude];//实时
         CLLocation *loc2=[[CLLocation alloc]initWithLatitude:_mapView.userLocation.coordinate.latitude longitude:_mapView.userLocation.coordinate.longitude];
         //计算两个位置之间的距离
         CLLocationDistance distance=[loc1 distanceFromLocation:loc2];
            self.kil+=distance;
    NSLog(@"-----距离--------%f",self.kil);
    self.kilLabel.text=[NSString stringWithFormat:@"距离(km):%.2f",self.kil/1000];
    CGFloat  min=[self.timer getTimeCounted]/60;
    if (min!=0) {
        self.speedLabel.text=[NSString stringWithFormat:@"速度(min/km):%.2f",self.kil/1000/min];
    }else{
        self.speedLabel.text=[NSString stringWithFormat:@"速度(min/km):%.2f",self.kil/1000];
    }
}
#pragma mark 离线地图的实现
-(void)initDownlodButton{
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pathButton.frame = CGRectMake(20, HEIGHT-60, 40, 40);
    pathButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    pathButton.backgroundColor = [UIColor whiteColor];
    [pathButton setImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
    
    [pathButton addTarget:self action:@selector(downlodMap:) forControlEvents:UIControlEventTouchUpInside];
//    [_mapView addSubview:pathButton];
    [self setupCities];
    [self initDownlodTableview];
}
-(void)setupCities{
    self.sectionTitles = @[@"全国", @"直辖市", @"省份"];
    self.cities = [MAOfflineMap sharedOfflineMap].cities;//普通城市和直辖市
    self.provinces = [MAOfflineMap sharedOfflineMap].provinces;//省
    self.municipalities = [MAOfflineMap sharedOfflineMap].municipalities;//直辖市
}
-(void)initDownlodTableview{
    self.downlodTableview =[[UITableView alloc]initWithFrame:CGRectMake(100, 50, WIDTH/3, HEIGHT/2) style:UITableViewStylePlain];
    self.downlodTableview.delegate=self;
    self.downlodTableview.dataSource =self;
}
-(void)downlodMap:(UIButton*)button{
    if (self.stopOrNo==YES) {
        [_mapView addSubview:self.downlodTableview];
    }else{
        [self.downlodTableview removeFromSuperview];
    }
    self.stopOrNo = !self.stopOrNo;
}

// 地图下载的几种状态
- (MAOfflineItem *)itemForIndexPath:(NSIndexPath *)indexPath{
    MAOfflineItem *item = nil;
    switch (indexPath.section){
        case 0:{
            item = [MAOfflineMap sharedOfflineMap].nationWide;//全国概要图
            break;
        }case 1:{
            item = self.municipalities[indexPath.row];//直辖市
            break;
        }case 2:{
            item =self.provinces[indexPath.row];
            break;
        }default:{
            MAOfflineProvince *pro = self.provinces[indexPath.section - self.sectionTitles.count];
            if (indexPath.row == 0){
                item = pro; //整个省
            }else{
                item = pro.cities[indexPath.row - 1]; //市
            }
            break;
        }
    }
    return item;
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_tableView ==  tableView) {
        return _pois.count;   //搜索
    }else if (self.downlodTableview==tableView){
        if (0==section) {
            return  1;  //全国
        }else if (1==section){  //直辖市
            return self.municipalities.count;
        }else if (2==section){   //省份
            return self.provinces.count;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_tableView==tableView) {  //搜索对象
        static NSString *cellIdentifier = @"cellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                          reuseIdentifier:cellIdentifier];
        }
        AMapPOI *poi = _pois[indexPath.row];  //AMapPOI携带者所有的返回的数据信息,可以直接赋值使用
        cell.textLabel.text = poi.name;
        cell.detailTextLabel.text = poi.address;
        NSLog(@"tbv搜索的结果是%@",cell.textLabel.text);
        return cell;
        
    }else{   //下载
        static NSString *resule =@"downlodCell";
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:resule];
        if (!cell) {
            cell =[[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:resule];
        }
        if (0==indexPath.section) {
            MAOfflineItem *item = [self itemForIndexPath:indexPath];
            NSLog(@"------ww--------%@",item.name);
            cell.textLabel.text = item.name;
            return cell;
        }else if (1==indexPath.section){
            MAOfflineItem *item = [self itemForIndexPath:indexPath];
            cell.textLabel.text = item.name;
            return cell;
        }else if(2==indexPath.section){
            MAOfflineItem *item = [self itemForIndexPath:indexPath];
            cell.textLabel.text = item.name;
            NSLog(@"------ww--------%@",item.name);
            return cell;
        }
    }
    return nil;
}
#pragma mark 点击方法,实现下载; 点击添加大头针
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.downlodTableview ==tableView) {
        MAOfflineItem *item = [self itemForIndexPath:indexPath];
        [self download:item];
    }else if(tableView==self.tableView){
        self.searchTextField.frame =CGRectMake(0, 0, 0, 0);
        self.tableView.frame =CGRectMake(0, 0, 0, 0);
        self.searchTextFieldBt.frame =CGRectMake(0, 0, 0, 0);
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        // 为点击的poi点添加标注
        AMapPOI *poi = _pois[indexPath.row];
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        annotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        annotation.title = poi.name;
        annotation.subtitle = poi.address;
        [_mapView addAnnotation:annotation];
        [_annotations addObject:annotation];
    }
}

#pragma 分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView==self.downlodTableview) {
        return self.sectionTitles.count;
    }else{
        return 1;
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView==self.downlodTableview) {
        if (0==section) {
            return @"全国";
        }else if (1==section){
            return @"直辖市";
        }else if (2==section){
            return @"省份";
        }else{
            return @"其他";
        }
    }else{
        return @"搜索列表";
    }
}


//下载某个离线地图数据项（参数 MAOfflineItem）
- (void)download:(MAOfflineItem *)item{
    if (item == nil || item.itemStatus == MAOfflineItemStatusInstalled){
        return;
    }
    NSLog(@"download :%@", item.name);
    [[MAOfflineMap sharedOfflineMap] downloadItem:item shouldContinueWhenAppEntersBackground:YES downloadBlock:^(MAOfflineMapDownloadStatus downloadStatus, id info) {
        /* Manipulations to your application’s user interface must occur on the main thread. */
        dispatch_async(dispatch_get_main_queue(), ^{
            if (downloadStatus == MAOfflineMapDownloadStatusWaiting){
                NSLog(@"状态为: %@", @"等待下载");
            }else if(downloadStatus == MAOfflineMapDownloadStatusStart){
                NSLog(@"状态为: %@", @"开始下载");
            }else if(downloadStatus == MAOfflineMapDownloadStatusProgress){
                NSLog(@"状态为: %@", @"正在下载");
            }else if(downloadStatus == MAOfflineMapDownloadStatusCancelled) {
                NSLog(@"状态为: %@", @"取消下载");
            }else if(downloadStatus == MAOfflineMapDownloadStatusCompleted) {
                NSLog(@"状态为: %@", @"下载完成");
            }else if(downloadStatus == MAOfflineMapDownloadStatusUnzip) {
                NSLog(@"状态为: %@", @"下载完成，正在解压缩");
            }else if(downloadStatus == MAOfflineMapDownloadStatusError) {
                NSLog(@"状态为: %@", @"下载错误");
            }else if(downloadStatus == MAOfflineMapDownloadStatusFinished) {
                NSLog(@"状态为: %@", @"全部完成");
                [_mapView reloadMap];              //激活离线地图
            }
        });
    }];
}
//暂停某个离线数据项
- (void)pause:(MAOfflineItem *)item{
    NSLog(@"pause :%@", item.name);
    [[MAOfflineMap sharedOfflineMap] pauseItem:item];
}
/**
 *  定位和搜索
 */
//初始化定位
- (void)initControls
{
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(20,  HEIGHT-150, 40, 40);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleTopMargin;   //uiview的自动调整高度
    _locationButton.backgroundColor = [UIColor whiteColor];
    _locationButton.layer.cornerRadius = 5;
    [_locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    [_mapView addSubview:_locationButton];
    
}
#pragma mark action
//定位用户的位置
-(void)locateAction{                                                           // 追踪用户的location更新
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)  {
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        //         @brief 缩放级别
        [_mapView setZoomLevel:kDefaultLocationZoomLevel animated:YES];
    }
}
#pragma mark - MAMapViewDelegate
// @ 定位用户位置的模式;替换定位按钮图标:使用mapView回调方法监听定位模式状态
- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    // 修改定位按钮状态
    if (mode == MAUserTrackingModeNone){
        [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }else{
        [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    }
}
#pragma mark - AMapSearchDelegate
//逆地理编码
// 搜索回调
- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"request :%@, error :%@", request, error);
}
//返回定位搜索的结果,所有的信息在response里面
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:
(AMapReGeocodeSearchResponse *)response{
    NSLog(@"response :%@", response);
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0){
        title = response.regeocode.addressComponent.province;
    }
    _mapView.userLocation.title = title;
    _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
}

// 在选中用户位置annotation时 弹出当前地址,弹出的窗口
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    // 选中定位annotation的时候进 逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]]){
        [self reGeoAction];
    }
}
#pragma mark - Helpers
// 发起搜索请求
- (void)reGeoAction{
    if (_currentLocation){
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude
                                                    longitude:_currentLocation.coordinate.longitude];//经纬度
        [_search AMapReGoecodeSearch:request];
    }
}
# pragma mark 第二部分实现地图的搜索兴趣点的功能
#pragma mark  init
//初始化所有的控件
-(void)initwithFrame{
     [self initAttributes]; //初始化数组
  //  [self initSearchButtonFrame];//搜索按钮
    [self initTableView];  //初始化tbv
}
-(void)initSearchButtonFrame{
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    searchButton.frame = CGRectMake(80, HEIGHT-120, 40, 40);
    searchButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    searchButton.backgroundColor = [UIColor whiteColor];
    [searchButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(initAction) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:searchButton];
}
//  初始化搜索对象
- (void)initSearch{
    [AMapSearchServices sharedServices].apiKey = @"fc3449e0365a0ce529efdead76bff0cc";
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest  *request = [[AMapPOIAroundSearchRequest alloc] init];
    NSLog(@"---经纬度----%f",_currentLocation.coordinate.latitude);
    request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude]; //精度和纬度
    request.keywords = self.searchText;         //textField的输入
    NSLog(@"搜索回调时-----%@",self.searchText);
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    request.requireExtension = YES;
    //发起周边搜索
    [_search AMapPOIAroundSearch: request];
}
//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    NSLog(@"观察数组变化%lu",(unsigned long)response.pois.count);
    if(response.pois.count == 0) {
        return ;//防止崩溃
    }
    //添加到数组里面方便我们查看
    if (response.pois.count > 0) {
        _pois = response.pois;   //pois 携带者所有返回的的数据
        NSLog(@"搜索的数组有---%@",_pois);
        [_tableView reloadData];
        // 清空标注
        [_mapView removeAnnotations:_annotations];
        [_annotations removeAllObjects];
    }
}
#pragma mark  init tbv
- (void)initTableView{
    _tableView   = [[UITableView alloc] init];
    _tableView.delegate   = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}
#pragma mark init Arr
- (void)initAttributes{
    _annotations = [NSMutableArray array];
    _pois = nil;
}
#pragma  action
- (void)initAction{
    [self initSearch];   //调用初始化对象
    self.tableView.frame =CGRectMake(0, 200,WIDTH, HEIGHT-200);
    [self initTextField]; //搜索框
}
-(void)initTextField{
    self.searchTextField = [[UITextField alloc]initWithFrame:CGRectMake((WIDTH-200)/2, 160, 200, 40)];
    self.searchTextField.placeholder = @"请您输入你想搜索的内容";
    self.searchTextField.textAlignment = NSTextAlignmentCenter;
    self.searchTextField.layer.borderWidth=0.5;
    self.searchTextField.layer.cornerRadius=5;
    self.searchTextField.layer.masksToBounds=YES;
    self.searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    [self.mapView addSubview:self.searchTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noticeTextField:) name:UITextFieldTextDidChangeNotification object:self.searchTextField];
    self.searchTextFieldBt =[UIButton buttonWithType:UIButtonTypeCustom ];
    [self.searchTextFieldBt setTitle:@"搜索" forState:UIControlStateNormal];
    self.searchTextFieldBt.frame = CGRectMake(self.searchTextField.frame.origin.x+220, 160, 40, 40);
    [self.searchTextFieldBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.searchTextFieldBt.layer.borderWidth=0.5;
    self.searchTextFieldBt.layer.cornerRadius=5;
    self.searchTextFieldBt.layer.masksToBounds=YES;
    [self.searchTextFieldBt addTarget:self action:@selector(searchPOI:) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:self.searchTextFieldBt];
}
#pragma 搜索的行为
-(void)searchPOI:(UIButton *)button{
  [self initSearch];  //开始搜搜
 
}
-(void)noticeTextField:(NSNotification*)notification{
    self.searchText = self.searchTextField.text;
}
//点击空白处回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.searchTextField resignFirstResponder];
}
//2 在MAMapView的回调函数中,取得或创建annotationView,并配置annotationView的属性
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil){
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;          //设置标注动画显示，默认为NO
        annotationView.draggable = YES;                 //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
#pragma 自定义大头针
//        annotationView.image =[UIImage imageNamed:@"ktv"]; //自定义的大头针
//        annotationView.canShowCallout =NO;
        // 设置中 点偏移,使得标注底部中间点成为经纬度对应点
//        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
    return nil;
}




















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
